<template>
  <div class="root gap-col-16 px-4 pt-2" :class="{ loading }">
    <div class="creator">
      <div v-if="result.creator_total > 0" class="gap-col-8">
        <div class="result-info">
          <i18n-t keypath="search.result.creators" tag="div">
            <template #keyword>
              <span class="text-primary">{{ searchText }}</span>
            </template>
            <template #num>
              <span>{{ result.creator_total }}</span>
            </template>
          </i18n-t>
          <div
            v-if="result.creator_total > 1"
            class="pointer watch-more"
            @click="setCurrentTab(SEARCH_RESULT_TYPE.CREATOR)"
          >
            {{ $t('common.watchMore') }}
            <Icon name="arrowRight" size="18"></Icon>
          </div>
        </div>
        <div class="creator-row" ref="outerElement">
          <div class="creator-container gap-row-5" ref="scrollElement">
            <CreatorAvatar
              v-for="item in result.creator"
              :key="`creator-${item.aff}`"
              :item="item"
              @click:item="onCreatorClick"
              ref="itemRefs"
            ></CreatorAvatar>
          </div>
          <SwipeArrow
            :show-left="showLeft"
            :show-right="showRight"
            :to-left="moveToLeft"
            :to-right="moveToRight"
            light-bg
          ></SwipeArrow>
        </div>
      </div>
    </div>
    <div class="video">
      <div v-if="result.video_total > 0" class="gap-col-8">
        <div class="result-info">
          <i18n-t keypath="search.result.videos" tag="div" class="font-size-14 font-weight-500 line-height-125">
            <template #keyword>
              <span class="text-primary">{{ searchText }}</span>
            </template>
            <template #num>
              <span>{{ result.video_total }}</span>
            </template>
          </i18n-t>
          <div
            v-if="result.video_total > 1"
            class="pointer watch-more"
            @click="setCurrentTab(SEARCH_RESULT_TYPE.VIDEO)"
          >
            {{ $t('common.watchMore') }}
            <Icon name="arrowRight" size="18"></Icon>
          </div>
        </div>
        <div class="media-container">
          <MediaRow :items="result.video" hide-last no-padding one-line @click:item="onVideoClick"></MediaRow>
        </div>
      </div>
    </div>
    <div class="image">
      <div v-if="result.image_total > 0" class="gap-col-8">
        <div class="result-info">
          <i18n-t keypath="search.result.photos" tag="div" class="font-size-14 font-weight-500 line-height-125">
            <template #keyword>
              <span class="text-primary">{{ searchText }}</span>
            </template>
            <template #num>
              <span>{{ result.image_total }}</span>
            </template>
          </i18n-t>
          <div
            v-if="result.image_total > 1"
            class="pointer watch-more"
            @click="setCurrentTab(SEARCH_RESULT_TYPE.PHOTO)"
          >
            {{ $t('common.watchMore') }}
            <Icon name="arrowRight" size="18"></Icon>
          </div>
        </div>
        <div class="media-container">
          <MediaRow :items="result.image" hide-last no-padding one-line @click:item="onPhotoClick"></MediaRow>
        </div>
      </div>
    </div>
    <div v-if="!result.creator_total && !result.video_total && !result.image_total">
      <div><ErrorNodata class="my-16"></ErrorNodata></div>
    </div>
  </div>
</template>
<script setup>
import { computed, onActivated, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useSearchResultStore, useSearchStore } from '@/store/search'
import ErrorNodata from '@/components/common/ErrorNodata.vue'
import SwipeArrow from '@/components/common/SwipeArrow.vue'
import MediaRow from '@/components/media/MediaRow.vue'
import CreatorAvatar from '@/components/multimedia/CreatorAvatar.vue'
import { useInfinite } from '@/compositions/request/infinite'
import { useHorizontalScroll } from '@/compositions/sensor/horizontal-scroll'
import { MEDIA_TYPE, SEARCH_RESULT_TYPE } from '@/constant'
import API from '@/http'

const searchStore = useSearchStore()
const { media } = storeToRefs(searchStore)
const { updateViewerRouterOriginPath, toIndexedMainViewer, toMainViewer, toCreatorViewer } = searchStore

const searchResultStore = useSearchResultStore()
const { setCurrentTab: $setCurrentTab } = searchResultStore
const { result, resultExist, searchText, hasSearchText } = storeToRefs(searchResultStore)
function setCurrentTab(v) {
  $setCurrentTab(v).then(updateViewerRouterOriginPath)
}

const loading = computed(() => !resultExist.value)

const fetcher = ref({
  video: useInfinite({
    request: API.Search.video,
    params: hasSearchText.value ? { keyword: searchText.value } : {},
    limit: import.meta.env.VITE_MEDIA_LIST_LIMIT ?? 12,
  }),
  photo: useInfinite({
    request: API.Search.image,
    params: hasSearchText.value ? { keyword: searchText.value } : {},
    limit: import.meta.env.VITE_MEDIA_LIST_LIMIT ?? 12,
  }),
})
onActivated(() => toMainViewer(fetcher.value))

watch(searchText, (keyword) => {
  if (!hasSearchText.value) {
    return
  }
  fetcher.value.video.refresh({ newParams: { type: MEDIA_TYPE.VIDEO, keyword } })
  fetcher.value.photo.refresh({ newParams: { type: MEDIA_TYPE.PHOTO, keyword } })
})

function onClick(mediaIndex, mediaType = MEDIA_TYPE.VIDEO) {
  if (mediaIndex === -1) {
    console.warn('No item found')
    return
  }
  media.value = mediaType
  toIndexedMainViewer(mediaIndex)
}

function onVideoClick(index) {
  const item = result.value.video[index] ?? null
  if (!item) {
    console.warn('No item found')
    return
  }
  const mediaIndex = fetcher.value.video.dataList.findIndex((i) => i.id === item.id)
  onClick(mediaIndex, MEDIA_TYPE.VIDEO)
}

function onPhotoClick(index) {
  const item = result.value.image[index] ?? null
  if (!item) {
    console.warn('No item found')
    return
  }
  const mediaIndex = fetcher.value.photo.dataList.findIndex((i) => i.id === item.id)
  onClick(mediaIndex, MEDIA_TYPE.PHOTO)
}

function onCreatorClick(aff, username) {
  toCreatorViewer(aff, username)
}

const outerElement = ref(null)
const scrollElement = ref(null)
const itemRefs = ref([])

const { showLeft, showRight, moveToLeft, moveToRight } = useHorizontalScroll(outerElement, scrollElement, itemRefs)
</script>
<style scoped lang="scss">
@import '@/assets/styles/loading-skeleton.scss';
.root {
  padding-bottom: 4.625rem;
}
.result-info {
  display: flex;
  justify-content: space-between;
  align-items: center;

  font-size: 0.875rem;
  font-weight: 500;
  line-height: 1.25rem;
}
.creator-container {
  position: relative;
  width: 100%;
  display: flex;

  padding-top: 0.125rem;
  overflow: auto;
}

.creator-row {
  position: relative;
}

.loading {
  .creator,
  .video,
  .image {
    width: 100%;
    height: 12rem;
  }

  .creator,
  .video,
  .image {
    @include loading-skeleton;
    border-radius: 0.625rem;
  }
}

.watch-more {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
